package com.zspringboot.demo.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zspringboot.demo.common.Constants;
import com.zspringboot.demo.controller.dto.UserDTO;
import com.zspringboot.demo.entity.Menu;
import com.zspringboot.demo.entity.User;
import com.zspringboot.demo.exception.ServiceException;
import com.zspringboot.demo.mapper.RoleMapper;
import com.zspringboot.demo.mapper.RoleMenuMapper;
import com.zspringboot.demo.mapper.UserMapper;
import com.zspringboot.demo.service.IMenuService;
import com.zspringboot.demo.service.IUserService;
import com.zspringboot.demo.utils.TokenUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author laolang
 * @since 2024-02-18
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Resource
    private RoleMapper roleMapper;

    @Resource
    private RoleMenuMapper roleMenuMapper;

    @Resource
    private UserMapper userMapper;
    @Resource
    private IMenuService iMenuService;
    @Override
    public UserDTO login(UserDTO user) {
        User one = getUserInfo(user);
        if (one!=null){
            // 拷贝user内容到one
            BeanUtil.copyProperties(one,user,true);
            // 设置Token
           String token =  TokenUtils.genToken(one.getId().toString(),one.getPassword());
            user.setToken(token);
            String role = one.getRole();
            // 设置用户的菜单列表
            List<Menu> roleMenus = getRoleMenus(role);
//            java.util.Collections.reverse(roleMenus);
            user.setMenus(roleMenus);
            return user;
        }else {
            throw new ServiceException(Constants.CODE_600,"用户名或密码错误");
        }

    }

    @Override
    public User register(UserDTO userDTO) {
        User one = getUserInfo(userDTO);
        if (one == null){
            one = new User();
            BeanUtil.copyProperties(userDTO,one,true);
            save(one);
        }else
            throw new ServiceException(Constants.CODE_600,"用户已存在！");
        return one;
    }

    @Override
    public Integer resetPassword(Integer id) {

        User u = userMapper.selectById(id);
        u.setPassword("123456");
        return  userMapper.updateById(u);
    }

    private User getUserInfo(UserDTO userDTO){
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username",userDTO.getUsername());
        queryWrapper.eq("password",userDTO.getPassword());
        User one;
        try{
            one = getOne(queryWrapper);// 从数据库查询信息
        }catch (Exception e){
            throw new ServiceException(Constants.CODE_500,"系统错误");
        }
        return one;
    }

    /**
     * 获取当前角色的菜单列表
     * @param role
     * @return
     */
    private List<Menu> getRoleMenus(String role){
        Integer roleId = roleMapper.selectByRoleKey(role);

        List<Integer> menuIds = roleMenuMapper.selectByRoleId(roleId);// 查出当前角色所有的关联菜单
        // 查出系统所有的菜单
        List<Menu> menus = iMenuService.findMenus("");
        List<Menu> roleMenus = new ArrayList<>();

        // 筛选当前用户拥有的菜单
        for (Menu menu : menus) {
            if (menuIds.contains(menu.getId())){ // contains 是否包含，包含返回true
                roleMenus.add(menu);
            }
            List<Menu> children =  menu.getChildren();
            // 移除children 里面不在 menuIds集合中的元素
            children.removeIf(child->!menuIds.contains(child.getId()));
        }
        return roleMenus;
    }
}
